﻿using ebMS3dotnet.Core.Configuration;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;

namespace ebMS3dotnet.Core
{
    public class ebMS3ServiceHost : ServiceHost
    {
        public ebMS3ServiceHost(string endpointConfiguration)
            : base(typeof(ebMS3Service))
        {
            Configure(endpointConfiguration);
        }

        private void Configure(string endpointID)
        {
            ebMS3ConfigurationSection configSection = (ebMS3ConfigurationSection)ConfigurationManager.GetSection("ebMS3dotnet");
            if (configSection == null)
                throw new ConfigurationErrorsException("The configuration section ebMS3dotnet could not be found.");

            EndpointCollection endpoints = configSection.Endpoints;
            if (endpoints.Count == 0)
                throw new ConfigurationErrorsException("No endpoints were found in the configuration file.");

            EndpointElement endpoint = endpoints[endpointID];
            if (endpoint == null)
                throw new ConfigurationErrorsException(string.Format("The endpoint with id {0} was not found in the configuration file.", endpointID));

            base.AddServiceEndpoint(typeof(IService), new ebMS3Binding(endpoint.SOAPVersion), endpoint.Address);
            base.Description.Behaviors.Add(new ebMS3ServiceBehavior());
        }
    }
}
